const fs = require('node:fs')

// 通过 window 对象向渲染进程注入 nodejs 能力
window.services = {
  execCommand(cmd, path) {
    if (!cmd) {
      return
    }
    let goPath = path ? 'tell current session to write text "cd "& quoted form of "' + path + '"' : ''
    require('child_process').exec(
      `osascript -e 'tell application "iTerm"
          activate
          try
              select current window
              tell current window
                  create tab with default profile
              end tell
              tell current window
                  ${goPath}
                  tell current session to write text "${cmd}"
              end tell
          on error
              select current window
              tell current window
                  ${goPath}
                  tell current session to write text "${cmd}"
              end tell
          end try
      end tell'`,
      (error, stdout, stderr) => {
        if (error) return window.utools.showNotification(stderr)
        window.utools.outPlugin()
      }
    )
  },
  export(data) {
    let savePath = utools.showSaveDialog({
      title: '导出位置',
      defaultPath: utools.getPath('downloads'),
      buttonLabel: '保存'
    })
    if (!savePath) return
    if (savePath.endsWith('/')) {
      window.utools.showNotification('文件名不能为空')
      return
    }
    const fileName = savePath.split('/').pop()
    fs.writeFileSync(fileName.includes('.') ? savePath : savePath + '.json', data, { encoding: 'utf-8' })
  },
  readFile (file) {
    return fs.readFileSync(file, { encoding: 'utf-8' })
  }
}
